package com.tyk.bookstore.back.logistics.service.impl;


import com.tyk.bookstore.back.common.core.util.IdGenerator;
import com.tyk.bookstore.back.common.dal.mapper.dto.SinDto;
import com.tyk.bookstore.back.logistics.model.entity.WaybillDo;
import com.tyk.bookstore.back.logistics.model.entity.WaybillTimelineDo;
import com.tyk.bookstore.back.logistics.model.enume.WaybillState;
import com.tyk.bookstore.back.logistics.model.query.WayBill4OrderAddQuery;
import com.tyk.bookstore.back.logistics.repository.WaybillRepository;
import com.tyk.bookstore.back.logistics.repository.WaybillTimelineRepository;
import com.tyk.bookstore.back.logistics.service.WaybillApiService;
import com.tyk.bookstore.back.logistics.util.MapStructLogistics;
import com.tyk.bookstore.back.logistics.util.WaybillUtil;
import com.tyk.bookstore.back.member.service.DeliveryAddressApiService;
import com.tyk.bookstore.back.storage.model.dto.Warehouse4WaybillDto;
import com.tyk.bookstore.back.storage.service.WarehouseApiService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigInteger;

/**
 * @author tyk
 * @description 运单对内暴露接口
 */
@Service
@RequiredArgsConstructor
public class WaybillApiServiceImpl implements WaybillApiService {
    private final WaybillRepository waybillRepository;
    private final WaybillTimelineRepository waybillTimelineRepository;
    private final WarehouseApiService warehouseApiService;
    private final DeliveryAddressApiService deliveryAddressApiService;
    private final MapStructLogistics mapStructLogistics;

    @Override
    public Long generateWaybill(WayBill4OrderAddQuery query) {

        // 仓库
        Warehouse4WaybillDto waybillDto = warehouseApiService.getWarehouse4WaybillDtoById(query.getWarehouseId());

        // 运单
        WaybillDo waybill = mapStructLogistics.toWaybillDo(query, waybillDto);

        // 运单号
        waybill.setTrackingNo(WaybillUtil.trackingNo()).setState(WaybillState.ORDERED);

        // 插入
        waybill.setId(IdGenerator.id());
        waybillRepository.insert(waybill);

        // 运单ID
        Long waybillId = waybill.getId();

        // 运单时间轴
        WaybillTimelineDo wtd = new WaybillTimelineDo().setWaybillId(waybillId).setOrderedTime(query.getOrderCreateTime());
        waybillTimelineRepository.insert(wtd);

        // 返回运单ID
        return waybillId;
    }

    @Override
    public Long getIdByTrackingNo(String trackingNo) {
        SinDto<BigInteger> dto = waybillRepository.<BigInteger>selectSin1Eq(
                WaybillDo::getId,
                WaybillDo::getTrackingNo, trackingNo,
                WaybillDo.class
        );
        if (dto == null) return null;
        return dto.getV1().longValue();
    }

}
